package com.lute.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.security.oauth2.common.json.JSONException;
import org.springframework.security.oauth2.common.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lute.model.Client;
import com.lute.model.ClientProfile;
import com.lute.model.Employee;
import com.lute.model.EmployeeProfile;
import com.lute.model.MailTemplate;
import com.lute.model.Role;
import com.lute.utils.DAOFactory;
import com.lute.utils.SendMail;
import com.lute.utils.ServerErrorResponse;

@Controller
public class NewEmployeeProfileInitServlet {
	
	@RequestMapping(value="/newUserProfile", method = RequestMethod.GET)
	public @ResponseBody String newUserProfile(HttpServletRequest request) throws JSONException {
		String result = "";
		JSONObject jsonRes = new JSONObject();
		
		HttpSession session = request.getSession(false);
		if(session == null) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_LOGGED_IN.toString());
			result = jsonRes.toString();
			return result;
		}
		
		/* check  authorization */
		String access = (String)session.getAttribute("profile");
		if( !(access.equals("noProfile")) ) {
			jsonRes.put("result", ServerErrorResponse.USER_NOT_ENTITLED.toString());
		}
		String ldapEmail = (String)session.getAttribute("ldapEmail");
		String profile = (String)session.getAttribute("profile");
		
		jsonRes.put("email", ldapEmail);
		jsonRes.put("clientId",JSONObject.NULL);
		jsonRes.put("clients", Client.getClientsIdAndName());
		
		try {
			
			if(profile.equals("exist") || profile.equals("created")) {
				Integer userId = (Integer)session.getAttribute("sessionUserId");
				String role = (String)session.getAttribute("role");
				EmployeeProfile employeeProfile = EmployeeProfile.getEmployeeProfileByEmployeeIdFromDB(role, userId);
				jsonRes.put("clientId",employeeProfile.getClient().getId_client());
				jsonRes.put("email", employeeProfile.getEmail());
			}		
		}catch(NullPointerException npe) {
			jsonRes.put("result", ServerErrorResponse.INTERNAL_ERROR.toString());
			result = jsonRes.toString();
			return result;
		}
		jsonRes.put("result", "OK");
		result = jsonRes.toString();
		return result;
	}
}
